package com.imay.live.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.imay.base.fragment.BaseFragment;
import com.imay.base.util.StringUtil;
import com.imay.live.IMApplication;
import com.imay.live.activity.ChatActivity;
import com.imay.live.activity.SystemNoticeActivity;
import com.imay.live.activity.family.FamilyHomeActivity;
import com.imay.live.activity.family.helper.NimLogin;
import com.imay.live.activity.family.helper.session.SessionHelper;
import com.imay.live.adapter.RecentContactAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.heartlikeslib.swipelayout.SwipeHorizontalMenuLayout;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.MediaHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.DataSetListener;
import com.imay.live.manager.DataSetManager;
import com.imay.live.manager.FamilyAccountManager;
import com.imay.live.manager.MessageManager;
import com.imay.live.manager.UnreadManager;
import com.imay.live.model.NewMailModel;
import com.imay.live.model.NotifyMessageModel;
import com.imay.live.model.RecentContactInfo;
import com.imay.live.model.RecentContactModel;
import com.imay.live.model.RecentFamilyModel;
import com.imay.live.model.SendMessageModel;
import com.imay.live.model.SystemNoticeModel;
import com.imay.live.model.UnreadModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultNoData;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.DialogUtil;
import com.imay.live.utils.ImayLogUtil;
import com.imay.live.utils.ModelCovertUtil;
import com.imay.live.utils.PermissionUtil;
import com.imay.live.utils.RecyclerViewUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.refresh.RefreshView;
import com.imay.live.R;
import com.imay.tbas_api.IMYTBASObject;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.netease.nim.uikit.cache.FriendDataCache;
import com.netease.nim.uikit.cache.TeamDataCache;
import com.netease.nim.uikit.common.ui.drop.DropManager;
import com.netease.nim.uikit.recent.TeamMemberAitHelper;
import com.netease.nim.uikit.team.helper.TeamExtendHelper;
import com.netease.nim.uikit.team.helper.TeamNotifyContentHelper;
import com.netease.nim.uikit.team.helper.TipMessageHelper;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.ResponseCode;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.QueryDirectionEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.team.model.Team;
import com.netease.nimlib.sdk.team.model.TeamMember;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static android.app.Activity.RESULT_OK;
import static com.imay.live.adapter.RecentContactAdapter.FAMILY;
import static com.imay.live.adapter.RecentContactAdapter.SYSTEM;
import static com.imay.live.adapter.RecentContactAdapter.USER;
import static com.imay.live.manager.UnreadManager.TYPE_UNREAD_FAMILY_MESSAGE;
import static com.imay.live.manager.UnreadManager.TYPE_UNREAD_MESSAGE;
import static com.imay.live.manager.UnreadManager.TYPE_UNREAD_SYSTEM_PROFILE;
import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * created by nick
 * 私信列表
 */
public class RecentContactListFragment extends BaseFragment implements ProtoCallBack, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener, DataSetListener {


    private String loadRecentContactCommand, loadSystemNoticeCommand;
    private TwinklingRefreshLayout trl_refresh_recent_contac;
    private RecyclerView rv_recent_contact;
    private int count = 20;
    private RecentContactModel recentContactModel;
    private List<MultiItemEntity> recentContactInfos;
    private int listOffset;
    private RecentContactAdapter contactAdapter;
    private IMYTBASObject messageReceiveListener, messageSendListener;
    private String deleteRecentContactCommand, ignoreRecentCommand;
    private int deletePosition;

    private final int systemnoticerequest = 1001; // 系统消息
    private final int personnoticerequest = 1002; // 个人消息

    private List<Integer> ignoreContentTypes;

    private boolean isInstance = true;
    private DataSetManager mDataSetManager;
    private boolean hasLoadFamily;
    private List<RecentContact> recentContactList;
    private boolean isNotFirstLoad;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_recent_contact_list;
    }

    public static RecentContactListFragment newInstance() {

        RecentContactListFragment fragment = new RecentContactListFragment();
        return fragment;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        recentContactInfos = new ArrayList<>();
        ignoreContentTypes = new ArrayList<>();
        recentContactList = new ArrayList<>();
        registerObservers(true);
        bindViews();
        loadData();
        mDataSetManager = DataSetManager.Builder.create(this).build();
        /*loadRecentContact();
        loadSystemNotice();*/
        addMessageReceiveListener();
    }

    private void bindViews() {
        trl_refresh_recent_contac = $(R.id.trl_refresh_recent_contac);
        rv_recent_contact = $(R.id.rv_recent_contact);
        RecyclerViewUtil.setLinearLayoutManagerWithoutDivider(getActivity(), rv_recent_contact);

        RefreshView headerView = new RefreshView(getActivity());
        trl_refresh_recent_contac.setHeaderView(headerView);
        trl_refresh_recent_contac.setBottomView(new LoadingView(getActivity()));
        trl_refresh_recent_contac.setEnableLoadmore(true);
        trl_refresh_recent_contac.setEnableOverScroll(false);
        trl_refresh_recent_contac.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                listOffset = 0;
                loadRecentContact();
                loadSystemNotice();
                loadFamilyData();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                listOffset = recentContactInfos.size();
                loadRecentContact();
            }
        });

    }

    private void loadRecentContact() {
        loadRecentContactCommand = ProtoRequestHelper.task(ProtoHttpFactory.getRecentContactList(listOffset, count)).setTag(this.hashCode()).request(this);
    }

    private void loadSystemNotice() {
        loadSystemNoticeCommand = ProtoRequestHelper.task(ProtoHttpFactory.getSystemNotice()).request(this);
    }


    @Override
    public void onRequestSuccess(String command, String data) {
        refreshFinish();
        if (command.equals(loadRecentContactCommand)) {
            Result<RecentContactModel> result = JSON.parseObject(data, new TypeReference<Result<RecentContactModel>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                if (listOffset == 0) {
                    clearListByType(RecentContactAdapter.USER);
                }
                recentContactInfos.addAll(result.data.getPersonalMailInfos());
                postUnreadEvent(TYPE_UNREAD_FAMILY_MESSAGE, hasUnread());
                bindAdapter();
            }
        } else if (command.equals(deleteRecentContactCommand)) {
            Result result = JSON.parseObject(data, new TypeReference<Result>() {
            }.getType());
            if (result.result == CodeSuccess) {
                recentContactInfos.remove(deletePosition);
                bindAdapter();
            }
        } else if (command.equals(ignoreRecentCommand)) {
            ResultNoData result = JSON.parseObject(data, ResultNoData.class);
            if (result.result == CodeSuccess) {
                setLocalMessageReaded();
                bindAdapter();
                ToastUtil.show(getActivity(), R.string.system_notice_ignore_toast2);
            }
        } else if (command.equals(loadSystemNoticeCommand)) {
            Result<List<SystemNoticeModel>> listResult = JSON.parseObject(data, new TypeReference<Result<List<SystemNoticeModel>>>() {
            }.getType());
            if (listResult.result == CodeSuccess) {
                List<SystemNoticeModel> systemNoticeModels = listResult.data;
                if (systemNoticeModels != null && !systemNoticeModels.isEmpty()) {
                    if (updateSystemNotice(systemNoticeModels)) {
                        // 发送一个通知红点
                        MessageManager.getInstance().postSystemRed();
                    }
                    clearListByType(SYSTEM);
                    SystemNoticeModel systemNoticeModel = systemNoticeModels.get(0);
                    recentContactInfos.add(0, systemNoticeModel);
                    bindAdapter();
                } else {
                    clearListByType(SYSTEM);
                    SystemNoticeModel systemNoticeModel = new SystemNoticeModel();
                    recentContactInfos.add(0, systemNoticeModel);
                    ignoreContentTypes.clear();
                    bindAdapter();
                }
            }
        }
    }

    /**
     * 更新系统通知信息
     *
     * @param systemNoticeModels
     * @return
     */
    private boolean updateSystemNotice(List<SystemNoticeModel> systemNoticeModels) {
        ignoreContentTypes.clear();
        boolean isHas = false;
        for (SystemNoticeModel systemNoticeModel : systemNoticeModels) {
            if (systemNoticeModel.getUnReadNum() > 0) {
                ignoreContentTypes.add(systemNoticeModel.getContentType());
                isHas = true;
            }
        }
        return isHas;
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        refreshFinish();
    }

    private void bindAdapter() {
        if (contactAdapter == null) {
            contactAdapter = new RecentContactAdapter(recentContactInfos);
            rv_recent_contact.setAdapter(contactAdapter);
            contactAdapter.setOnItemChildClickListener(this);
            contactAdapter.setOnItemClickListener(this);
            contactAdapter.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.view_load_layout, null));
        } else {
            contactAdapter.setNewData(recentContactInfos);
        }
        clearRedPoint();
        trl_refresh_recent_contac.setEnableLoadmore(!recentContactInfos.isEmpty());
    }

    @Override
    public void onItemChildClick(final BaseQuickAdapter adapter, final View view, final int position) {
        switch (view.getId()) {
            case R.id.tv_system_notice_delete:
                DialogUtil.getNormalDialog(getActivity(), getString(R.string.delete_warning), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SwipeHorizontalMenuLayout layout = (SwipeHorizontalMenuLayout) view.getParent().getParent();
                        layout.smoothCloseMenu();
                        MultiItemEntity entity = (MultiItemEntity) adapter.getData().get(position);
                        if (entity.getItemType() == USER) {
                            deleteRecentContact(((RecentContactInfo) recentContactInfos.get(position)).getUserChannelId());
                            deletePosition = position;
                        } else if (entity.getItemType() == FAMILY) {
                            NIMClient.getService(MsgService.class).deleteRecentContact2(((RecentFamilyModel) recentContactInfos.get(position)).getContactId(), SessionTypeEnum.Team);
                        }

                    }
                }).show();
                break;
        }
    }


    private void refreshFinish() {
        if (trl_refresh_recent_contac != null) {
            trl_refresh_recent_contac.finishLoadmore();
            trl_refresh_recent_contac.finishRefreshing();
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        switch (recentContactInfos.get(position).getItemType()) {
            case RecentContactAdapter.USER:
                RecentContactInfo info = (RecentContactInfo) recentContactInfos.get(position);
                ChatActivity.startActivityForResult(getActivity(), info.getYourUid(), info.getYourNick(), personnoticerequest);
                info.setUnReadRecordCount(0);
                adapter.notifyItemChanged(position);
                clearRedPoint();
                break;
            case RecentContactAdapter.SYSTEM:
                SystemNoticeActivity.startActivityForResult(getActivity(), systemnoticerequest);
                break;
            case RecentContactAdapter.FAMILY:
                final RecentFamilyModel familyModel = (RecentFamilyModel) recentContactInfos.get(position);
                if (TeamExtendHelper.isFamilyLocked(familyModel.getContactId())) {
                    ToastUtil.show(getActivity(), R.string.family_locked);
                    break;
                }
                SessionHelper.startTeamSession(getContext(), familyModel.getContactId());

//                PermissionUtil.requestStoragePermission(getContext(), new PermissionListener() {
//                    @Override
//                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
//                        SessionHelper.startTeamSession(getContext(), familyModel.getContactId());
//                    }
//
//                    @Override
//                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
//                        SessionHelper.startTeamSession(getContext(), familyModel.getContactId());
//                        //PermissionUtil.showStoragePermissionDialog(getContext(), deniedPermissions);
//                    }
//                });

                familyModel.setUnreadCount(0);
                clearRedPoint();
                break;
        }

    }

    private void addMessageReceiveListener() {
        messageReceiveListener = new IMYTBASObject(false);
        messageReceiveListener.stringCommand = EventHelper.EVENT_MESSAGE_NOTIFY;
        messageReceiveListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
                NotifyMessageModel notifyMessageModel = JSON.parseObject(imytbasObject.stringData, new TypeReference<NotifyMessageModel>() {
                }.getType());
                refreshViewAfterMessageNotify(notifyMessageModel);
            }
        });
        messageReceiveListener.addEventListenWithTBASObject();

        messageSendListener = new IMYTBASObject(false);
        messageSendListener.stringCommand = EventHelper.EVENT_MESSAGE_SEND;
        messageSendListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
//                Log.e("stringData",imytbasObject.stringData);
                SendMessageModel messageModelResult = JSON.parseObject(imytbasObject.stringData, SendMessageModel.class);
                if (messageModelResult.getNewListInfo() != null && messageModelResult.getNewListInfo().size() > 0) {
                    if (isHasFamaly()) {
                        recentContactInfos.addAll(2, messageModelResult.getNewListInfo());
                    } else {
                        recentContactInfos.addAll(1, messageModelResult.getNewListInfo());
                    }
                } else {
                    refreshViewAfterMessageSend(messageModelResult);
                }
                if (getActivity() != null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            bindAdapter();
                        }
                    });
                }
            }
        });
        messageSendListener.addEventListenWithTBASObject();
    }

    private void refreshViewAfterMessageSend(SendMessageModel model) {
        if (recentContactInfos != null) {
            for (int i = 0; i < recentContactInfos.size(); i++) {
                if (recentContactInfos.get(i).getItemType() == RecentContactAdapter.USER) {
                    RecentContactInfo info = (RecentContactInfo) recentContactInfos.get(i);
                    if (model.getUserChannelId().equals(info.getUserChannelId())) {
                        info.setLatestMsg(model.getContentLocal());
                        info.setLatestMsgTime(model.getTimeStamp());
                        break;
                    }
                }
            }
        }

    }

    private void refreshViewAfterMessageNotify(NotifyMessageModel notifyMessageModel) {
        boolean hasMeaege = false;
        if (recentContactInfos != null) {
            for (int i = 0; i < recentContactInfos.size(); i++) {
                if (recentContactInfos.get(i).getItemType() == RecentContactAdapter.USER) {
                    RecentContactInfo info = (RecentContactInfo) recentContactInfos.get(i);
                    if (notifyMessageModel.getUserChannelId().equals(info.getUserChannelId())) {
                        info.setLatestMsg(notifyMessageModel.getContent());
                        if (IMApplication.getInstance().getCurrentChatUid() != info.getYourUid()) {
                            info.setUnReadRecordCount(info.getUnReadRecordCount() + 1);
                        }
                        recentContactInfos.remove(i);
                        if (isHasFamaly()) {
                            recentContactInfos.add(2, info);
                        } else {
                            recentContactInfos.add(1, info);
                        }
                        hasMeaege = true;
                        break;
                    }
                }
            }
            if (!hasMeaege) {
                if (isHasFamaly()) {
                    recentContactInfos.add(2, ModelCovertUtil.convertNotifyMessageModel(notifyMessageModel));
                } else {
                    recentContactInfos.add(1, ModelCovertUtil.convertNotifyMessageModel(notifyMessageModel));
                }
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    bindAdapter();
                }
            });
        }

    }

    private void deleteRecentContact(String userChannelId) {
        deleteRecentContactCommand = ProtoRequestHelper.task(ProtoHttpFactory.deleteRecentContact(userChannelId)).setTag(this.hashCode()).request(this);
    }

    public void ignoreRecentMessage() {
        ignoreRecentCommand = ProtoRequestHelper.task(ProtoHttpFactory.ignorePersonalMail(ignoreContentTypes)).setTag(this.hashCode()).request(this);
        clearFamilyUnread();
    }

    private void clearRedPoint() {
        if (!hasUnread()) {
            UnreadManager.getInstance().postUnreadEvent(TYPE_UNREAD_MESSAGE, 0);
        }

    }

    public boolean hasUnread() {
        if (recentContactInfos == null || recentContactInfos.size() == 0) {
            return false;
        }
        boolean hasUnread = false;
        if (ignoreContentTypes != null && !ignoreContentTypes.isEmpty()) {
            return true;
        }
        for (MultiItemEntity item : recentContactInfos) {
            if (item.getItemType() == RecentContactAdapter.USER) {
                RecentContactInfo info = (RecentContactInfo) item;
                if (info.getUnReadRecordCount() > 0) {
                    hasUnread = true;
                    break;
                }
            } else if (item.getItemType() == RecentContactAdapter.FAMILY) {
                RecentFamilyModel info = (RecentFamilyModel) item;
                if (info.getUnreadCount() > 0) {
                    hasUnread = true;
                    break;
                }
            }
        }
        return hasUnread;

    }

    boolean isCreated;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreated = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 友盟统计页面跳转，重写此方法，可以保证ViewPager切换Fragment时能够准确的记录Fragment之间的跳转
        // 不用再调用Fragment的生命周期方法
        if (isCreated) {
            if (isVisibleToUser) {
                MobclickAgent.onPageStart(getClass().getSimpleName());
            } else {
                MobclickAgent.onPageEnd(getClass().getSimpleName());
            }
        }
    }

    private void setLocalMessageReaded() {
        ignoreContentTypes.clear();
        if (recentContactInfos == null || recentContactInfos.size() == 0) {
            return;
        }
        for (MultiItemEntity item : recentContactInfos) {
            if (item.getItemType() == RecentContactAdapter.USER) {
                RecentContactInfo info = (RecentContactInfo) item;
                info.setUnReadRecordCount(0);
            } else if (item.getItemType() == RecentContactAdapter.SYSTEM) {
                SystemNoticeModel info = (SystemNoticeModel) item;
                info.setUnReadNum(0);
            }
        }
        postUnreadEvent(TYPE_UNREAD_FAMILY_MESSAGE, false);
        postUnreadEvent(TYPE_UNREAD_MESSAGE, false);
        postUnreadEvent(TYPE_UNREAD_SYSTEM_PROFILE, false);


    }

    public int getUnreadCount() {
        if (recentContactInfos == null || recentContactInfos.size() == 0) {
            return 0;
        }
        int unreadCount = 0;
        for (MultiItemEntity item : recentContactInfos) {
            if (item.getItemType() == RecentContactAdapter.USER) {
                RecentContactInfo info = (RecentContactInfo) item;
                unreadCount += info.getUnReadRecordCount();
            }
//            else if(item.getItemType() == RecentContactAdapter.FAMILY){
//                RecentFamilyModel info = (RecentFamilyModel) item;
//                unreadCount += info.getUnreadCount();
//            }
        }
        return unreadCount;
    }


    @Override
    public void loadData() {
        if (isCreate) {
            if (AccountManager.getInstance().isLogined()) {
                if (isInstance) {
                    isInstance = false;
                    listOffset = 0;
                    loadRecentContact();
                    loadSystemNotice();

                }
            }
        }
    }

    public void loadFamily() {
        if (NimLogin.getInstance().isLoginNim() && !hasLoadFamily) {
            hasLoadFamily = true;
            loadFamilyData();
        }

    }

    @Override
    public void clearData() {
        recentContactInfos.clear();
        isInstance = true;
    }

    @Override
    public void onDestroy() {
        if (mDataSetManager != null) {
            mDataSetManager.unregisterDataNotify();
        }
        registerObservers(false);
        super.onDestroy();

    }

    /**
     * 判断需不需要清空数据
     *
     * @return
     */
    private boolean isFirstSystem() {
        return recentContactInfos.size() > 0 &&
                recentContactInfos.get(0).getItemType() == RecentContactAdapter.SYSTEM;
    }

    /**
     * 判断有没有家族信息
     *
     * @return
     */
    private boolean isHasFamaly() {
        return recentContactInfos.size() > 1 &&
                recentContactInfos.get(1).getItemType() == FAMILY;
    }

    /**
     * 刷新系统通知
     */
    public void refreshSystemNotify() {
        loadSystemNotice();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == systemnoticerequest) {
            refreshSystemNotify();
        } else if (requestCode == personnoticerequest) {
            if (resultCode == RESULT_OK) {
                listOffset = 0;
                loadRecentContact();
            }
        }
    }

    private void loadFamilyData() {
        // 查询最近联系人列表数据
        NIMClient.getService(MsgService.class).queryRecentContacts().setCallback(new RequestCallbackWrapper<List<RecentContact>>() {

            @Override
            public void onResult(int code, List<RecentContact> recents, Throwable exception) {
                if (code != ResponseCode.RES_SUCCESS || recents == null) {
                    return;
                }
                //初次加载，更新离线的消息中是否有@我的消息
                for (RecentContact recentContact : recents) {
                    if (recentContact.getSessionType() == SessionTypeEnum.Team) {
                        updateOfflineContactAited(recentContact);
                    }
                }
                recentContactList.addAll(recents);
                if (listOffset == 0) {
                    clearListByType(FAMILY);
                }
                List<RecentFamilyModel> recentFamilyList = new ArrayList<>();
                for (RecentContact contact : recents) {
                    if (contact.getSessionType() == SessionTypeEnum.Team) {
                        Team team = TeamDataCache.getInstance().getTeamById(contact.getContactId());
                        if (team != null && team.isMyTeam()) {
                            recentFamilyList.add(RecentFamilyModel.getRecentFamilyModel(contact));
                        }
                    }
                }
                if (isFirstSystem()) {
                    recentContactInfos.addAll(1, recentFamilyList);
                } else {
                    recentContactInfos.addAll(0, recentFamilyList);
                }
                postUnreadEvent(TYPE_UNREAD_FAMILY_MESSAGE, hasUnread());
                bindAdapter();


            }
        });
    }

    private void updateOfflineContactAited(final RecentContact recentContact) {
        if (recentContact == null || recentContact.getSessionType() != SessionTypeEnum.Team
                || recentContact.getUnreadCount() <= 0) {
            return;
        }

        // 锚点
        List<String> uuid = new ArrayList<>(1);
        uuid.add(recentContact.getRecentMessageId());

        List<IMMessage> messages = NIMClient.getService(MsgService.class).queryMessageListByUuidBlock(uuid);

        if (messages == null || messages.size() < 1) {
            return;
        }
        final IMMessage anchor = messages.get(0);

        // 查未读消息
        NIMClient.getService(MsgService.class).queryMessageListEx(anchor, QueryDirectionEnum.QUERY_OLD,
                recentContact.getUnreadCount() - 1, false).setCallback(new RequestCallbackWrapper<List<IMMessage>>() {

            @Override
            public void onResult(int code, List<IMMessage> result, Throwable exception) {
                if (code == ResponseCode.RES_SUCCESS && result != null) {
                    result.add(0, anchor);
                    Set<IMMessage> messages = null;
                    // 过滤存在的@我的消息
                    for (IMMessage msg : result) {
                        if (TeamMemberAitHelper.isAitMessage(msg)) {
                            if (messages == null) {
                                messages = new HashSet<>();
                            }
                            messages.add(msg);
                        }
                    }

                    // 更新并展示
                    if (messages != null) {
                        TeamMemberAitHelper.setRecentContactAited(recentContact, messages);
                        //TODO
                    }
                }
            }
        });

    }

    /**
     * 删除列表中指定类型数据
     */
    private void clearListByType(int type) {
        Iterator<MultiItemEntity> it = recentContactInfos.iterator();
        while (it.hasNext()) {
            MultiItemEntity entity = it.next();
            if (entity.getItemType() == type) {
                it.remove();
            }
        }

    }


    /**
     * ********************** 收消息，处理状态变化 ************************
     */
    private void registerObservers(boolean register) {
        MsgServiceObserve service = NIMClient.getService(MsgServiceObserve.class);
        service.observeReceiveMessage(messageReceiverObserver, register);
        service.observeRecentContact(messageObserver, register);
//        service.observeMsgStatus(statusObserver, register);
        service.observeRecentContactDeleted(deleteObserver, register);
        service.observeCustomNotification(commandObserver, register);


//        registerTeamUpdateObserver(register);
//        registerTeamMemberUpdateObserver(register);
//        FriendDataCache.getInstance().registerFriendDataChangedObserver(friendDataChangedObserver, register);
//        if (register) {
//            registerUserInfoObserver();
//        } else {
//            unregisterUserInfoObserver();
//        }
    }

    // 暂存消息，当RecentContact 监听回来时使用，结束后清掉
    private Map<String, Set<IMMessage>> cacheMessages = new HashMap<>();

    //监听在线消息中是否有@我
    private Observer<List<IMMessage>> messageReceiverObserver = new Observer<List<IMMessage>>() {
        @Override
        public void onEvent(List<IMMessage> imMessages) {
            if (imMessages != null) {
                for (IMMessage imMessage : imMessages) {
                    if (!TeamMemberAitHelper.isAitMessage(imMessage)) {
                        continue;
                    }
                    Set<IMMessage> cacheMessageSet = cacheMessages.get(imMessage.getSessionId());
                    if (cacheMessageSet == null) {
                        cacheMessageSet = new HashSet<>();
                        cacheMessages.put(imMessage.getSessionId(), cacheMessageSet);
                    }
                    cacheMessageSet.add(imMessage);
                }
            }
        }
    };

    Observer<List<RecentContact>> messageObserver = new Observer<List<RecentContact>>() {
        @Override
        public void onEvent(List<RecentContact> recentContacts) {
            if (recentContacts == null) {
                return;
            }

            List<RecentFamilyModel> recentFamilyList = new ArrayList<>();
            for (RecentContact contact : recentContacts) {
                if (contact.getSessionType() == SessionTypeEnum.Team && cacheMessages.get(contact.getContactId()) != null) {
                    TeamMemberAitHelper.setRecentContactAited(contact, cacheMessages.get(contact.getContactId()));
                }
                if (contact.getSessionType() == SessionTypeEnum.Team) {
                    recentFamilyList.add(RecentFamilyModel.getRecentFamilyModel(contact));
                }

            }
            cacheMessages.clear();
            clearListByType(FAMILY);
            if (isFirstSystem()) {
                recentContactInfos.addAll(1, recentFamilyList);
            } else {
                recentContactInfos.addAll(0, recentFamilyList);
            }
            bindAdapter();
            postUnreadEvent(TYPE_UNREAD_FAMILY_MESSAGE, hasUnread());
        }
    };

    Observer<RecentContact> deleteObserver = new Observer<RecentContact>() {
        @Override
        public void onEvent(RecentContact recentContact) {
            clearListByType(FAMILY);
            bindAdapter();
            clearRedPoint();

        }
    };

    /**
     * 命令消息接收观察者
     */
    Observer<CustomNotification> commandObserver = new Observer<CustomNotification>() {
        @Override
        public void onEvent(CustomNotification message) {
//            if (message.getSessionType() != SessionTypeEnum.Team) {
//                return;
//            }
            ImayLogUtil.log("CustomNotification",message.getContent());
            if (FamilyAccountManager.getInstance().isHasFamilyInfo()) {
                String teamId = FamilyAccountManager.getInstance().getFamilyUserInfo().getFamily().getTid();
                if (!StringUtil.isEmpty(teamId)) {
                    String content = TeamNotifyContentHelper.getContentByCustomerNotifyMessage(message.getContent());
                    if (!StringUtil.isEmpty(content)) {
                        TipMessageHelper.insertTipMessage(teamId, content);
                    }
                }
            }


        }
    };


    private void postUnreadEvent(int type, boolean hasUnread) {
        UnreadManager.getInstance().postUnreadEvent(type, hasUnread ? 1 : 0);
    }


    private void clearFamilyUnread() {
        if (recentContactInfos != null) {
            for (MultiItemEntity entity : recentContactInfos) {
                if (entity.getItemType() == FAMILY) {
                    RecentFamilyModel familyModel = (RecentFamilyModel) entity;
                    NIMClient.getService(MsgService.class).clearUnreadCount(familyModel.getContactId(), SessionTypeEnum.Team);
                }

            }
        }
    }


}

